﻿<%@ WebHandler Language="VB" Class="OrderDetailJson" %>

Imports System
Imports System.Web
Imports System.Data
Imports VSModel
Imports Newtonsoft.Json
Imports System.Xml
Imports System.IO
Imports System.Web.Script.Serialization
Public Class OrderDetailJson : Implements IHttpHandler
    
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim json As String
        Dim oOrderId As Integer = 0
        If HttpContext.Current.Request.QueryString("OrderId") IsNot Nothing Then
            oOrderId = CType(HttpContext.Current.Request.QueryString("OrderId"), Int32)
        End If

        Using data As New VSEntities
            Dim ds As New DataSet("OrderDetails")
            
            Dim dt As DataTable = CreateDtOrderDetail()
            Dim p = (From o In data.BanHangDetails Where o.BanHangId = oOrderId).ToList

            If Not p Is Nothing AndAlso p.Count > 0 Then
                For Each item In p
                    Dim dr As DataRow = dt.NewRow()
                    dr("Code") = item.ProductCode
                    dr("Title") = item.Product.Title
                    dr("Number") = item.Number
                    dt.Rows.Add(dr)
                Next
                ds.Tables.Add(dt)
            Else
                Dim dr As DataRow = dt.NewRow()
                dr("Code") = DBNull.Value
                dr("Title") = DBNull.Value
                dr("Number") = DBNull.Value
        
                dt.Rows.Add(dr)
                ds.Tables.Add(dt)
            End If

            'Finally convert DataSet to JSON format
            json = Ds2Json(ds)

            'Set ContentType return to
            context.Response.ContentType = "application/json; charset=utf-8"
            context.Response.Write(json)
        End Using
    End Sub
    
    Public Shared Function Ds2Json(ByVal ds As DataSet) As String
        Dim sw As New StringWriter()
        ds.WriteXml(sw, XmlWriteMode.IgnoreSchema)
        Dim xd As New XmlDocument()
        xd.LoadXml(sw.ToString())

        Dim jsonText As String = JsonConvert.SerializeXmlNode(xd)
        Return jsonText
    End Function
    
    Public Function CreateDtOrderDetail() As DataTable
        Dim dt As New DataTable("OrderDetail")
        Dim dc As New DataColumn()
        dc = New DataColumn("Code", System.Type.[GetType]("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("Title", System.Type.[GetType]("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("Number", System.Type.[GetType]("System.Int32"))
        dt.Columns.Add(dc)
       
        
        Return dt
    End Function
    
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class